//
// Created by 11311 on 2022/12/26.
//

#ifndef HEURISTIC_TSPLIB_HPP
#define HEURISTIC_TSPLIB_HPP
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
double *get_row(char *buff){
    double *res = (double*) malloc(2 * sizeof(double));

    char bf[1024] = {'\0'};
    int idx = 0;
    int count = 0;
    int flag = 0;
    for(int i = 0;buff[i]!='\0';i++){
        if(buff[i]>='0' && buff[i] <= '9'){
            bf[idx] = buff[i];
            idx++;
            flag = 1;
        } else if(flag == 1){
            bf[idx] = '\0';
            idx = 0;
            count++;
            flag = 0;
        }
        if(count > 0 && flag == 0){

            res[count - 1] = atof(bf);
        }
    }

    return res;
}

double **get_matrix(double **nodes, int node_num){
    double **res = (double **)malloc(node_num * sizeof(double *));
    int double_block_size = sizeof(double);
    for(int i = 0; i < node_num; i++){
        res[i] = (double *)malloc(node_num * double_block_size);
        for(int j = 0; j < node_num; j++){
            res[i][j] = pow(pow(nodes[i][0] - nodes[j][0], 2.0) + pow(nodes[i][1] - nodes[j][1], 2.0), 0.5);
        }
    }
    return res;
}


double** read_file_node(const char *file){
    char buff[1024] = {'\0'};
    int count = 0;
    int row = 0;

    int len = strlen(file);
    for(int i = len - 5; i>=0 ; i--){
        if(file[i] < '0' || file[i]> '9')break;
        row += pow(10, count) * (file[i] - '0');
        count++;
    }

    double **res = (double **)malloc(row * sizeof(double*));

    FILE *infile = fopen64(file, "r");
    if(!infile){
        cout<<"the file open filed!\n";
        exit(-2);
    }

    count = 0;
    int flag = 0;
    while (fgets(buff,1024,infile)){
        if(flag == 0){

            if(strcmp("NODE_COORD_SECTION\n", buff)==0 || strcmp("EDGE_WEIGHT_SECTION\n",buff) == 0)flag = 1;
            continue;
        }

        double *p = get_row(buff);
        res[count] = p;
        count++;
    }

    double **result = get_matrix(res, row);
    for(int i = 0; i < row; i++)free(res[i]);
    free(res);
    return result;
}




#endif //HEURISTIC_TSPLIB_HPP
